<template>
  <a-upload
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :before-upload="onBefore"
  >
    <img v-if="localSrc" :src="localSrc" alt="avatar"/>
    <div v-else>
      <plus-outlined/>
      <div class="ant-upload-text">Upload</div>
    </div>
  </a-upload>
</template>

<script setup lang="ts">
import {ref, watch} from 'vue';
import {PlusOutlined} from '@ant-design/icons-vue';
import {message} from 'ant-design-vue';

/* v-model 语法糖：props + emit */
const props = defineProps<{ avatar: File | null }>();
const emit = defineEmits<{ 'update:avatar': [f: File | null] }>();

const localSrc = ref<string>('');

/* 文件校验 + 预览 */
const onBefore = (file: File) => {
  const isImg = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/webp';
  if (!isImg) return message.error('推荐上传jpg,jpeg,png,webp格式的文件'), false;
  if (file.size / 1024 / 1024 > 2) return message.error('图片不能大于2MB'), false;

  emit('update:avatar', file);          // 把 File 抛给父级
  const reader = new FileReader();
  reader.onload = e => localSrc.value = e.target!.result as string;
  reader.readAsDataURL(file);
  return false;                         // 阻止默认上传
};

/* 外部清空时同步本地预览 */
watch(() => props.avatar, v => !v && (localSrc.value = ''));
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

img {
  max-width: 100%;
}
</style>
